package com.dongke.service.Impl;

import com.dongke.mapper.Role1Mapper;
import com.dongke.mapper.Role1Menu1Mapper;
import com.dongke.pojo.Role1;
import com.dongke.pojo.Role1Menu1Example;
import com.dongke.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private Role1Mapper role1Mapper;
    @Autowired
    private Role1Menu1Mapper role1Menu1Mapper;
    @Override
    public PageInfo<Role1> selectInfo(Role1 role, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<Role1> roles = role1Mapper.selectByName(role);
        PageInfo<Role1> rolePageInfo = new PageInfo<>(roles);
        return rolePageInfo;
    }

    @Override
    public boolean deleteInfoById(Integer rid) {
        int i = role1Mapper.deleteByPrimaryKey(rid);
        Role1Menu1Example role1Menu1Example = new Role1Menu1Example();
        Role1Menu1Example.Criteria criteria = role1Menu1Example.createCriteria();
        criteria.andRidEqualTo(rid);
        int i1 = role1Menu1Mapper.deleteByExample(role1Menu1Example);
        if(i > 0 && i1 > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean addRoleInfo(Role1 role, Integer[] mids) {
//先增加角色表，后返回主键ID
        int i = role1Mapper.inserInfoReturnId(role);
//获取角色主键id
        Integer rid = role.getRid();
        //增加角色权限
                int i2 = role1Menu1Mapper.insertBatch(rid, mids);
                return i2 > 0;
    }

    @Override
    public Role1 selectById(Integer id) {
        Role1 role1 = role1Mapper.selectByPrimaryKey(id);
        return role1;
    }

    @Override
    public boolean updateRoleById(Role1 role, Integer[] mids) {
        //先修改角色信息
        role1Mapper.updateByPrimaryKeySelective(role);
        //再删除原有的角色权限
        Role1Menu1Example role1Menu1Example = new Role1Menu1Example();
        Role1Menu1Example.Criteria criteria = role1Menu1Example.createCriteria();
        criteria.andRidEqualTo(role.getRid());
        role1Menu1Mapper.deleteByExample(role1Menu1Example);
        //再增加
        int i = role1Menu1Mapper.insertBatch(role.getRid(), mids);
        return i>0;
    }

    @Override
    public List<Role1> selectRole() {
        List<Role1> role1s = role1Mapper.selectByExample(null);
        return role1s;
    }

}
